<template>
  <div class="min-h-screen bg-gray-100">
    <!-- 连接状态覆盖层 -->
    <div
      v-if="!connectionStatus && !connectionError"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-lg p-8 text-center">
        <div
          class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"
        ></div>
        <p class="text-lg font-medium text-gray-800">连接中...</p>
        <p class="text-sm text-gray-600 mt-2">正在连接到房间 {{ roomId }}</p>
      </div>
    </div>

    <!-- 连接错误覆盖层 -->
    <div
      v-if="connectionError"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    >
      <div class="bg-white rounded-lg p-8 text-center max-w-md">
        <div class="text-red-500 mb-4">
          <svg
            class="w-16 h-16 mx-auto mb-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            ></path>
          </svg>
        </div>
        <h3 class="text-lg font-medium text-gray-800 mb-2">连接失败</h3>
        <p class="text-sm text-gray-600 mb-4">{{ connectionError }}</p>
        <div class="flex gap-3 justify-center">
          <button
            @click="retryConnection"
            :disabled="isReconnecting"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300 transition-colors"
          >
            {{ isReconnecting ? "重连中..." : "重试" }}
          </button>
          <button
            @click="$router.push('/')"
            class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
          >
            返回首页
          </button>
        </div>
      </div>
    </div>

    <div class="game-layout min-h-screen flex flex-col" :class="layoutClass">
      <!-- 头部信息栏 -->
      <header class="game-header bg-white shadow-sm">
        <div class="flex flex-col md:flex-row md:items-center gap-2 p-2 md:p-4">
          <div class="flex flex-wrap items-center gap-2 md:gap-4">
            <h2 class="text-base md:text-xl font-bold text-gray-800">
              房间: {{ roomId }}
            </h2>
            <div
              class="flex items-center gap-1 md:gap-2 text-xs md:text-sm text-gray-600"
            >
              <div
                class="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full"
                :class="connectionStatus ? 'bg-green-500' : 'bg-red-500'"
              ></div>
              <span>{{ connectionStatus ? "已连接" : "连接中..." }}</span>
            </div>
            <!-- 游戏状态指示器 -->
            <div
              v-if="gameState.gameStatus !== 'waiting'"
              class="flex items-center gap-1 md:gap-2 text-xs md:text-sm"
            >
              <span class="text-gray-600"
                >第 {{ gameState.round || 1 }} /
                {{ gameState.maxRounds || 5 }} 轮</span
              >
              <div class="w-12 md:w-16 bg-gray-200 rounded-full h-1">
                <div
                  class="bg-blue-500 h-1 rounded-full transition-all duration-300"
                  :style="{ width: `${gameProgress}%` }"
                />
              </div>
            </div>
          </div>
          <button
            @click="leaveGame"
            class="px-3 py-1.5 md:px-4 md:py-2 bg-gray-500 text-white text-sm rounded-lg hover:bg-gray-600 transition-colors"
          >
            退出房间
          </button>
        </div>
      </header>

      <!-- 主游戏区域 -->
      <main class="game-main flex-1 flex flex-col md:flex-row md:p-4 gap-4">
        <!-- 画板区域 -->
        <div class="canvas-area relative flex-1">
          <DrawingCanvas
            :is-drawer="isCurrentDrawer"
            :disabled="gameState.gameStatus !== 'drawing'"
            :show-tools="isCurrentDrawer && gameState.gameStatus === 'drawing'"
            @stroke-added="handleStrokeAdded"
            @canvas-cleared="handleCanvasCleared"
          />
          <div
            v-if="gameState.gameStatus === 'waiting'"
            class="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90"
          >
            <div class="text-center">
              <svg
                class="w-16 h-16 mx-auto mb-4 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"
                ></path>
              </svg>
              <p class="text-lg font-medium text-gray-600 mb-2">
                等待更多玩家加入
              </p>
              <p class="text-sm text-gray-500">需要至少2个玩家才能开始游戏</p>
            </div>
          </div>

          <div
            v-else-if="gameState.gameStatus === 'finished'"
            class="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90"
          >
            <div class="text-center">
              <svg
                class="w-16 h-16 mx-auto mb-4 text-green-500"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                ></path>
              </svg>
              <p class="text-lg font-medium text-gray-800 mb-4">游戏结束！</p>
              <button
                @click="$router.push('/')"
                class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
              >
                返回首页
              </button>
            </div>
          </div>
        </div>

        <!-- 猜词面板 -->
        <div class="guess-panel-wrapper md:w-80 lg:w-96">
          <div class="md:sticky md:top-4">
            <GuessPanel
              :is-drawer="isCurrentDrawer"
              :current-word="gameState.currentWord"
              :time-left="gameState.timeLeft"
              :game-status="gameState.gameStatus"
              :players="gameState.players"
              :messages="gameState.messages || []"
              :current-round="gameState.round"
              :max-rounds="gameState.maxRounds"
              :game-progress="gameProgress"
              :can-start-game="canStartGame"
              :is-mobile="isMobile"
              :is-collapsed="isPanelCollapsed"
              @toggle-collapse="togglePanelCollapse"
              @guess="handleGuess"
              @start-game="handleStartGame"
            />
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useGameStore } from "../stores/game";
import { useUserStore } from "../stores/user";
import { useGameConfigStore } from "../stores/gameConfig";
import DrawingCanvas from "../components/DrawingCanvas.vue";
import GuessPanel from "../components/GuessPanel.vue";
import type { DrawStroke } from "../types/game";

const route = useRoute();
const router = useRouter();
const gameStore = useGameStore();
const userStore = useUserStore();
const gameConfigStore = useGameConfigStore();

const roomId = ref("");
const isPanelCollapsed = ref(false);

// 计算属性
const gameState = computed(() => gameStore.gameState);
const isCurrentDrawer = computed(() => gameStore.isCurrentDrawer);
const isMobile = computed(() => window.innerWidth < 768);

// 切换面板折叠状态
const togglePanelCollapse = () => {
  isPanelCollapsed.value = !isPanelCollapsed.value;
};
const connectionStatus = computed(() => gameStore.isConnected);
const connectionError = computed(() => gameStore.connectionError);
const isReconnecting = computed(() => gameStore.isReconnecting);
const gameProgress = computed(() => gameStore.gameProgress);
const canStartGame = computed(() => gameStore.canStartGame);

const layoutClass = computed(() => ({
  "layout-mobile": isMobile.value,
  "layout-desktop": !isMobile.value,
}));

// 事件处理
const handleStrokeAdded = (stroke: DrawStroke) => {
  console.log("新笔画已同步:", stroke.id);
};

const handleCanvasCleared = () => {
  console.log("画布清除已同步");
};

const handleGuess = (guess: string) => {
  console.log("猜测已发送:", guess);
};

const handleStartGame = () => {
  gameStore.startGame();
};

const retryConnection = async () => {
  const playerName = `玩家${Math.floor(Math.random() * 1000)}`;
  await gameStore.connectToRoom(roomId.value, playerName);
};

const leaveGame = () => {
  gameStore.disconnectFromRoom();
  gameStore.resetGameState();
  router.push("/");
};

const initializeGame = async () => {
  roomId.value = (route.params.roomId as string) || "DEMO";

  try {
    // 使用用户设置的昵称
    const playerName = userStore.displayName;
    const connected = await gameStore.connectToRoom(roomId.value, playerName);

    if (connected) {
      // 连接成功后设置用户ID
      userStore.setPlayerId(gameStore.currentPlayer?.id || "");
      console.log("成功连接到房间:", roomId.value);
    } else {
      console.error("连接失败");
    }
  } catch (error) {
    console.error("初始化游戏失败:", error);
  }
};

onMounted(() => {
  initializeGame();
  console.log("游戏页面已加载，房间ID:", roomId.value);
});

onUnmounted(() => {
  gameStore.disconnectFromRoom();
});
</script>

<style scoped>
.game-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.game-header {
  flex-shrink: 0;
}

.game-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 手机端布局 */
.layout-mobile .game-main {
  flex-direction: column;
}

.layout-mobile .canvas-area {
  flex: 1;
  min-height: 0;
  position: relative;
}

/* 电脑端布局 */
.layout-desktop .game-main {
  flex-direction: row;
  position: relative;
}

.layout-desktop .canvas-area {
  flex: 1;
  padding: 20px;
  position: relative;
}

/* 确保画布容器填满可用空间 */
.canvas-area {
  display: flex;
  flex-direction: column;
  min-height: 0;
}
</style>
